import Taro, { Component } from '@tarojs/taro'
import { View, ScrollView } from '@tarojs/components'
import { connect } from '@tarojs/redux'
import { AtInput, AtSwitch } from 'taro-ui'
import classNames from 'classnames'
import * as actions from '@actions/address'
import { getList } from '@utils/area.js'
import { setGlobalData, getGlobalData } from '@store/global_data'

import './addressAdd.scss'

@connect(state => state.address, actions)
class AddressAdd extends Component {
  config = {
    navigationBarTitleText: '编辑地址'
  }

  constructor (props) {
    super(props)
    this.state = {
      address: {
        id: 0,
        areaCode: 0,
        address: '',
        name: '',
        phone: '',
        defaulted: false,
        province: '',
        city: '',
        county: ''
      },
      addressId: this.$router.params.id ? this.$router.params.id : 0,
      openSelectRegion: false,
      selectRegionList: [
        {
          code: 0,
          name: '省份'
        },
        {
          code: 0,
          name: '城市'
        },
        {
          code: 0,
          name: '区县'
        }
      ],
      regionType: 1,
      regionList: [],
      selectRegionDone: false
    }
  }

  componentDidShow() {
    if (this.state.addressId && this.state.addressId != 0) {
      this.props.dispatchAddressInfo({
        id: this.state.addressId
      }).then((data) => {
        this.setState({
          address: data
        })
      })
    }
  }

  handleNameChange (value) {
    let address = this.state.address
    address.name = value;
    this.setState({ address: address })
    return value
  }

  handlePhoneChange (value) {
    let address = this.state.address
    address.phone = value;
    this.setState({ address: address })
    return value
  }

  handleAddressChange (value) {
    let address = this.state.address
    address.address = value;
    this.setState({ address: address })
    return value
  }

  handleDefaultChange = (value) => {
    let address = this.state.address
    address.defaulted = value;
    this.setState({ address: address })
    return value
  }

  handleSave = () => {
    // 校验
    if (this.state.address.name === '') {
      Taro.showToast({
        title: '请输入姓名',
        icon: 'none',
      });
      return;
    }
    if (!/^1[234578]\d{9}$/.test(this.state.address.phone)) {
      Taro.showToast({
        title: '手机号格式不正确',
        icon: 'none',
      });
      return;
    }
    if (this.state.address.region === '') {
      Taro.showToast({
        title: '请选择收货地址',
        icon: 'none',
      });
      return;
    }
    if (this.state.address.address === '') {
      Taro.showToast({
        title: '请输入详细地址',
        icon: 'none',
      });
      return;
    }

    this.props.dispatchAddressSave(this.state.address).then(data => {
      let pages = Taro.getCurrentPages()
      let prevPage = pages[pages.length - 2]
      if (prevPage.route == "pages/orderSettlement/orderSettlement") {
        setGlobalData('orderSettlement-addressId', data.id)
      }
      Taro.navigateBack()
    })
  }

  setRegionDoneStatus() {
    let doneStatus = this.state.selectRegionList.every(item => {
      return item.code != 0;
    });

    this.setState({
      selectRegionDone: doneStatus
    })
  }

  chooseRegion() {
    const { address, selectRegionList, openSelectRegion } = this.state

    this.setState({
      openSelectRegion: !openSelectRegion
    })

    //设置区域选择数据
    if (address.areaCode > 0) {
      selectRegionList[0].code = address.areaCode.slice(0, 2) + '0000'
      selectRegionList[0].name = address.province

      selectRegionList[1].code = address.areaCode.slice(0, 4) + '00'
      selectRegionList[1].name = address.city

      selectRegionList[2].code = address.areaCode
      selectRegionList[2].name = address.county

      let regionList = getList('county', address.areaCode.slice(0, 4))
      regionList = regionList.map(item => {
        //标记已选择的
        if (address.areaCode === item.code) {
          item.selected = true
        } else {
          item.selected = false
        }
        return item
      })

      this.setState({
        selectRegionList: selectRegionList,
        regionType: 3,
        regionList: regionList
      })
    } else {
      let newRegionList = [
        {
          code: 0,
          name: '省份',
        },
        {
          code: 0,
          name: '城市',
        },
        {
          code: 0,
          name: '区县',
        }
      ]

      this.setState({
        selectRegionList: newRegionList,
        regionType: 1,
        regionList: getList('province')
      })
    }

    this.setRegionDoneStatus()
  }

  selectRegionType(regionTypeIndex) {
    const { selectRegionList, regionType } = this.state

    //判断是否可点击
    if (regionTypeIndex + 1 == regionType || (regionTypeIndex - 1 >= 0 && selectRegionList[regionTypeIndex - 1].code <= 0)) {
      return false
    }

    let selectRegionItem = selectRegionList[regionTypeIndex]
    let code = selectRegionItem.code
    let regionList
    if (regionTypeIndex === 0) {
      // 点击省级，取省级
      regionList = getList('province')
    }
    else if (regionTypeIndex === 1) {
      // 点击市级，取市级
      regionList = getList('city', code.slice(0, 2))
    }
    else{
      // 点击县级，取县级
      regionList = getList('county', code.slice(0, 4))
    }

    regionList = regionList.map(item => {
      //标记已选择的
      if (selectRegionList[regionTypeIndex].code == item.code) {
        item.selected = true
      } else {
        item.selected = false
      }
      return item
    })

    this.setState({
      regionList: regionList,
      regionType: regionTypeIndex + 1
    })

    this.setRegionDoneStatus()
  }

  selectRegion(regionIndex) {
    const { selectRegionList, regionType } = this.state
    let regionItem = this.state.regionList[regionIndex]
    selectRegionList[regionType - 1] = regionItem;

    if (regionType == 3) {
      this.setState({
        selectRegionList: selectRegionList
      })

      let regionList = this.state.regionList.map(item => {
        //标记已选择的
        if (selectRegionList[regionType - 1].code == item.code) {
          item.selected = true
        } else {
          item.selected = false
        }
        return item
      })

      this.setState({
        regionList: regionList
      })

      this.setRegionDoneStatus()
      return
    }

    //重置下级区域为空
    selectRegionList.map((item, index) => {
      if (index > regionType - 1) {
        item.code = 0
        item.name = index == 1 ? '城市' : '区县'
      }
      return item
    })

    this.setState({
      selectRegionList: selectRegionList,
      regionType: regionType + 1
    })

    let code = regionItem.code
    let regionList = []
    if (regionType === 1) {
      // 点击省级，取市级
      regionList= getList('city', code.slice(0, 2))
    }
    else {
      // 点击市级，取县级
      regionList= getList('county', code.slice(0, 4))
    }

    this.setState({
      regionList: regionList
    })

    this.setRegionDoneStatus()
  }

  doneSelectRegion() {
    if (this.state.selectRegionDone === false) {
      return false
    }

    let address = this.state.address
    let selectRegionList = this.state.selectRegionList
    address.province = selectRegionList[0].name
    address.city = selectRegionList[1].name
    address.county = selectRegionList[2].name
    address.areaCode = selectRegionList[2].code

    this.setState({
      address: address,
      openSelectRegion: false
    })

  }

  cancelSelectRegion() {
    this.setState({
      openSelectRegion: false,
      regionType: this.state.selectRegionDone ? 3 : 1
    })
  }

  render () {
    const { address, openSelectRegion, selectRegionList, selectRegionDone } = this.state
    return (
      <View className='address-add'>
        <AtInput name='name' type='text' placeholder='姓名' value={address.name} onChange={this.handleNameChange.bind(this)} />
        <AtInput name='phone' type='phone' placeholder='手机号码' value={address.phone} onChange={this.handlePhoneChange.bind(this)} />
        <AtInput name='region' type='text' placeholder='省份、城市、区县' value={address.province + address.city + address.county} editable={false} onClick={this.chooseRegion.bind(this)} />
        <AtInput name='address' type='text' placeholder='详细地址,如街道、楼盘号等' value={address.address} onChange={this.handleAddressChange.bind(this)} />
        <AtSwitch title='设为默认地址' checked={this.state.address.defaulted} onChange={this.handleDefaultChange} />

        <View className='address-add__footer' onClick={this.handleSave}>
          保存
        </View>

        {
          openSelectRegion &&
          <View className='region__select'>
            <View className='region__select-hd'>
              <View className='region__select-hd-selected'>
                {selectRegionList.map((item,index) => {
                  return (
                    <View key={item.code} onClick={this.selectRegionType.bind(this,index)} className={classNames('region__select-hd-item', item.code === 0 && 'region__select-hd-item-disabled', (this.state.regionType -1) === index && 'region__select-hd-item-selected')} >
                      {item.name}
                    </View>
                  )
                })}
              </View>
              <View className={classNames('region__select-hd-done', !selectRegionDone && 'region__select-hd-disabled')} onClick={this.doneSelectRegion.bind(this)}>确定</View>
            </View>
            <View className='region__select-bd'>
              <ScrollView scrollY className='region__select-list'>
                {this.state.regionList.map((item,index) => {
                  return (
                    <View key={item.code} className={classNames('region__select-bd-item',  item.selected && 'region__select-bd-selected')} onClick={this.selectRegion.bind(this,index)}>{item.name}
                    </View>
                  )
                })}
              </ScrollView>
            </View>
          </View>
        }

        {openSelectRegion && <View className='bg-mask' onClick={this.cancelSelectRegion.bind(this)}></View>}

      </View>
    )
  }
}

export default AddressAdd
